package com.hsteach.framework.web.service;

import com.hsteach.common.core.domain.model.AuthInfo;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.framework.feign.ClientConstant;
import com.hsteach.framework.feign.client.auth.dto.AuthResp;
import com.hsteach.framework.feign.client.upload.UploadClient;
import com.hsteach.framework.feign.client.upload.dto.UploadEntity;
import com.hsteach.framework.feign.client.upload.vo.UploadRet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.OutputStream;

@Service
public class UploadService {

    @Autowired
    private UploadClient uploadClient;

    public UploadRet upload(Workbook workbook, String fileName) {
        MultipartFile file = workbookToCommonsMultipartFile(workbook, fileName);
        UploadEntity entity = new UploadEntity();
        entity.setFile(file);
        AuthInfo authInfo = SecurityUtils.getAuthInfo();
        AuthResp<UploadRet> resp = uploadClient.push(authInfo.getAccessToken(), authInfo.getAppToken(), ClientConstant.UPLOAD_OPERATE_CODE_DEFAULT, entity);
        if (isSuccess(resp)) {
            return  resp.getResult();
        } else {
            throw new ServiceException("upload api error: " + resp.getMessage());
        }
    }

    public static MultipartFile workbookToCommonsMultipartFile(Workbook workbook, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem fileItem = factory.createItem("file", "text/plain", true, fileName);
        try {
            OutputStream os = fileItem.getOutputStream();
            workbook.write(os);
            os.close();
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            return multipartFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private boolean isSuccess(AuthResp resp) {
        if (ClientConstant.AUTH_SUCCESS.equals(resp.getStatus())) {
            return true;
        }
        return false;
    }
}
